import { useState, useEffect } from 'react';

type SetStateAction<T> = T | ((prevState: T) => T);

export function useLocalStorage<T>(key: string, initialValue: T) {
    const [value, setValue] = useState<T>(() => {
        const storedValue = localStorage.getItem(key);
        return storedValue ? JSON.parse(storedValue) : initialValue;
    });

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    const updateValue = (newValue: SetStateAction<T>) => {
        setValue(prev => {
            const next = newValue instanceof Function ? newValue(prev) : newValue;
            return next;
        });
    };

    return [value, updateValue] as const;
}
